package com.phonemap.common;

import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import com.google.appengine.api.datastore.Entity;
import com.phonemap.models.Photo;
import com.phonemap.models.Position;
import com.phonemap.models.User;

public class InitEntity {
	
	public static void initDatabase() {
		Iterable<Entity> positions = Position.getAllPositions();
		
		Iterable<Entity> photos = Photo.getAllPhotos();
		
		Iterable<Entity> users = User.getAllUsers();
		 
		List<Entity> newPositions = new ArrayList<Entity>();
		List<Entity> newPhotos = new ArrayList<Entity>();
		List<Entity> newUsers = new ArrayList<Entity>();
		//Delete position
		for (Entity position : positions) {
			newPositions.add(position);
			Position.deletePosition(position.getKey().getName());
		}
		//Delete photo entity
		for (Entity photo : photos) {
			newPhotos.add(photo);
			Photo.deletePhoto(photo.getKey().getName());
		}
		//Delete User entity
		for (Entity user : users) {
			newUsers.add(user);
			User.deleteUser(user.getKey().getName());
		}
		
		//Input data into User
		//Insert new entities
		for (Entity entity : newUsers) {
			Entity user = new Entity("User", entity.getKey().getName());
			user.setProperty("phone", entity.getKey().getName());
			user.setProperty("firstname", entity.getProperty("firstname"));
			user.setProperty("lastname", entity.getProperty("lastname"));
			user.setProperty("email", entity.getProperty("email"));
			user.setProperty("password", entity.getProperty("password"));
			user.setProperty("avatar", entity.getProperty("avatar"));
			
			user.setProperty("workAndEducation", "");
			user.setProperty("live", "");
			user.setProperty("birthday", "");
			user.setProperty("interestedIn", "");
			user.setProperty("relationshipStatus", "");
			user.setProperty("mobilePhone", "");
			user.setProperty("website", "");
			user.setProperty("introduction", "");
			user.setProperty("status", "1");
			Util.persistEntity(user);
		}
		
		//Insert data into Position
		for (Entity entity : newPositions) {
			Entity position = new Entity("Position", entity.getParent());
			position.setProperty("userId", entity.getProperty("userId"));
			position.setProperty("latitude", entity.getProperty("latitude"));
			position.setProperty("longitude", entity.getProperty("longitude"));
			position.setProperty("positionDate", entity.getProperty("positionDate"));
			Util.persistEntity(position);
		}
		
		//Insert data into Photo
		for (Entity entity : newPhotos) {
			Entity photo = new Entity("Photo", entity.getParent());
			photo.setProperty("userId", entity.getProperty("userId"));
			photo.setProperty("title", entity.getProperty("title"));
			photo.setProperty("caption", entity.getProperty("caption"));
			photo.setProperty("contentType", entity.getProperty("contentType"));
			photo.setProperty("photoData", entity.getProperty("photoData"));
			photo.setProperty("photoPath", entity.getProperty("photoPath"));
			photo.setProperty("photoDate", entity.getProperty("photoDate"));
			Util.persistEntity(photo);
		}
		
	}
	
	public static void insertUsers() {
		Iterable<Entity> oldUsers = User.getAllUsers();
		Iterable<Entity> oldPositions = Position.getAllPositions();
		//Delete User entity
		for (Entity oldUser : oldUsers) {
			User.deleteUser(oldUser.getKey().getName());
		}
		
		for (Entity oldPos : oldPositions) {
			Position.deletePosition(oldPos.getKey().getName());
		}
		
		String content = getContent("C:\\workspace\\dev\\gophonemap\\war\\user.txt");
		List<String> users = getUsers(content);
		long phone = 913630243;
		for (String username : users) {
			String fullname = username.substring(username.indexOf("@_@", 0) + 3, username.length());
			int endIndexOfFistname = getEndIndexOfFistname(fullname);
			
			Entity user = new Entity("User", "0" + Long.toString(phone));
			user.setProperty("phone", "0" + Long.toString(phone));
			user.setProperty("firstname", fullname.substring(0, endIndexOfFistname));
			user.setProperty("lastname", fullname.substring(endIndexOfFistname + 1, fullname.length()));
			user.setProperty("email", fullname.replaceAll(" ", "_") + "@facebook.com");
			user.setProperty("password", "e10adc3949ba59abbe56e057f20f883e");
			user.setProperty("avatar", username.substring(0, username.indexOf("@_@", 0)));
			
			user.setProperty("workAndEducation", "");
			user.setProperty("live", "");
			user.setProperty("birthday", "");
			user.setProperty("interestedIn", "");
			user.setProperty("relationshipStatus", "");
			user.setProperty("mobilePhone", "0" + Long.toString(phone));
			user.setProperty("website", "");
			user.setProperty("introduction", "");
			user.setProperty("status", "1");
			Util.persistEntity(user);
			phone++;
		}
		
		List<String> positions = getPositions("C:\\workspace\\dev\\gophonemap\\war\\position.txt");
		int endIndex;
		for (String pos : positions) {
			endIndex = pos.indexOf("@_@", 0);
			Entity user = User.getSingleUser("0" + pos.substring(0, endIndex));
			if (user != null) {
				//double latitude = Double.parseDouble(pos.substring(endIndex + 3, pos.indexOf(",", endIndex+3)));
				//double longitude = Double.parseDouble(pos.substring(pos.indexOf(",", endIndex+3)+1, pos.length()));
				
				BigDecimal latitude = BigDecimal.valueOf(Double.parseDouble(pos.substring(endIndex + 3, pos.indexOf(",", endIndex+3))));
				BigDecimal longitude = BigDecimal.valueOf(Double.parseDouble(pos.substring(pos.indexOf(",", endIndex+3)+1, pos.length())));
				
				Calendar cal = Calendar.getInstance();
		        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
				
				Entity position;
				
				position = new Entity("Position", user.getKey());
				position.setProperty("userId", user.getKey().getName());
				position.setProperty("latitude", latitude.toString());
				position.setProperty("longitude", longitude.toString());
				position.setProperty("positionDate", new Date());
				Util.persistEntity(position);
				
				latitude = latitude.add(BigDecimal.valueOf(0.003));
				longitude = longitude.add(BigDecimal.valueOf(0.003));
				cal.add(Calendar.DATE, -1);
				
				position = new Entity("Position", user.getKey());
				position.setProperty("userId", user.getKey().getName());
				position.setProperty("latitude", latitude.toString());
				position.setProperty("longitude", longitude.toString());
				position.setProperty("positionDate", cal.getTime());
				Util.persistEntity(position);
				
				latitude = latitude.add(BigDecimal.valueOf(0.003));
				longitude = longitude.add(BigDecimal.valueOf(0.003));
				cal.add(Calendar.DATE, -2);
				
				
				position = new Entity("Position", user.getKey());
				position.setProperty("userId", user.getKey().getName());
				position.setProperty("latitude", latitude.toString());
				position.setProperty("longitude", longitude.toString());
				position.setProperty("positionDate", cal.getTime());
				Util.persistEntity(position);
				
			}
		}
		
		
	}
	
	private static int getEndIndexOfFistname(String name) {
		int fromIndex = 0;
		while (name.indexOf(" ", fromIndex) != -1) {
			fromIndex = name.indexOf(" ", fromIndex+1);
			break;
		}
		
		return fromIndex;
	}
	
	private static String getContent(String filename) {
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(filename));
			StringBuilder sb = new StringBuilder();
	        String line = br.readLine();

	        while (line != null) {
	            sb.append(line);
	            sb.append(System.lineSeparator());
	            line = br.readLine();
	        }
	        String content = sb.toString();
	        br.close();
	        return content;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
	    }
		return null;
	}
	
	private static List<String> getPositions(String filename) {
		List<String> positions = new ArrayList<String>();
		
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(filename));
	        String line = br.readLine();

	        while (line != null) {
	            positions.add(line);
	            line = br.readLine();
	        }
	        br.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
	    }
		return positions;
	}
	
	private static List<String> getUsers(String content) {
		List<String> users = new ArrayList<String>();
		int fromIndex = 0;
		int endIndex;
		String user = "";
		while (content.indexOf("class=\"_s0 _rv img\" src=\"", fromIndex) != -1) {
        	fromIndex = content.indexOf("class=\"_s0 _rv img\" src=\"", fromIndex);
        	fromIndex += 25;
			endIndex = content.indexOf(".jpg", fromIndex);
			user = content.substring(fromIndex , endIndex + 4);
			fromIndex = endIndex + 4;
			//substring name
			fromIndex = content.indexOf("div class=\"fsl fwb fcb\"", fromIndex);
			fromIndex = content.indexOf("\">", fromIndex + 24);
			endIndex = content.indexOf("</a>", fromIndex);
			user = user + "@_@" + content.substring(fromIndex + 2 , endIndex);
			users.add(user);
		}
		return users;
	}
	
}
